<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Validator;
use DB;
use App\Services\Helper;

class ForgotPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset emails and
    | includes a trait which assists in sending these notifications from
    | your application to your users. Feel free to explore this trait.
    |
    */


    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    protected function validator(array $data)
    {
        $code = session("forget");
        $messages = [
            'code.required' => '验证码必须填写',
            'code.in' => '验证码不正确',
            'username.required' => '手机必须填写',
            'username.phone' => '手机格式不正确',
            'username.unique' => '手机已经被注册',
            'password.required' => '密码必须填写',
            'password.min' => '密码必须大于6位',
        ];

        return Validator::make($data, [
            'code' => 'required|in:'. $code,
            'username' => 'required|phone|max:255',
            'password' => 'required|min:6',
        ],$messages);
    }    

    public function forget(Request $request) 
    {
        $data['username'] = $request->input('username');
        $data['password'] = $request->input('password');
        $data['code'] = $request->input('code');   

        $validatorMsg = $this->validator($data);
        if ($validatorMsg->fails()) {
            return Helper::jsonError($validatorMsg->errors()->first());
        }
        $result = $this->update($data, $uid);
        if ($result) {                
            //更新密码               
            return Helper::jsonSuccess('密码修改成功');      
        } else {
            return Helper::jsonError('密码修改失败，请重试');
        }     
    }

    protected function update(array $data, $uid)
    {
        return  DB::table('users')->where('uid', $uid)->update(['password' => bcrypt($data['password'])]);
    }
}
